import router from "@/router";
import store from "@/store"
import accessEnum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
    // console.log("登录用户信息", store.state.user.loginUser);
    //自动登录
    let loginUser = store.state.user.loginUser;
    //若没登陆过，自动登录
    if(!loginUser || !loginUser.userRole ||
        loginUser.userRole === accessEnum.NOT_LOGIN) {
        //await: 等用户登录成功，再执行后续代码
        console.log("自动登录...")
        await store.dispatch("user/getLoginUser");
        loginUser = store.state.user.loginUser;
    }
    const needAccess = (to.meta?.access as string) ?? accessEnum.NOT_LOGIN;
    console.log("登录用户信息", store.state.user.loginUser);
    // console.log("needAccess:", needAccess);
    if(needAccess !== accessEnum.NOT_LOGIN) {
        // console.log("需要登录才能访问的页面")
        if(!loginUser || !loginUser.userRole ||
            loginUser.userRole === accessEnum.NOT_LOGIN) {
            // console.log("!loginUser ? ", !loginUser, ", loginUser: ", loginUser);
            // console.log("!loginUser.userRole ? ", !loginUser.userRole, ", loginUser.userRole: ", loginUser.userRole);
            // console.log("loginUser.userRole === accessEnum.NOT_LOGIN ? ", loginUser.userRole === accessEnum.NOT_LOGIN,
            //     ", loginUser.userRole: ", loginUser.userRole, "accessEnum.NOT_LOGIN: ", accessEnum.NOT_LOGIN);
            next(`/user/login?redirect=${to.fullPath}`)
            return;
        }
        if(!checkAccess(loginUser, needAccess as string)) {
            // console.log("登录但是权限不够")
            next('/noAuth');
            return;
        }
    }
    next();
})